import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { Picker } from '@ant-design/react-native';
import FontAwesome from '@expo/vector-icons/FontAwesome';

interface TimePickerProps {
  value?: string;
  onChange?: (time: string) => void;
  placeholder?: string;
  disabled?: boolean;
}

const TimePicker: React.FC<TimePickerProps> = ({ 
  value = '07:00', 
  onChange, 
  placeholder = "选择时间",
  disabled = false 
}) => {
  const [visible, setVisible] = useState(false);
  const [currentTime, setCurrentTime] = useState(value);

  // 生成时间选项
  const generateTimeOptions = () => {
    const options = [
      { value: 'none', label: '不使用时间触发' }  // 添加这一项
    ];
    for (let hour = 0; hour < 24; hour++) {
      for (let minute = 0; minute < 60; minute += 10) {
        const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        options.push({ value: timeStr, label: timeStr });
      }
    }
    return options;
  };

  const timeOptions = generateTimeOptions();

  const handleTimeChange = (value: any) => {
    const selectedTime = value[0];
    console.log('Time changed:', selectedTime);

    if (selectedTime === 'none') {
      setCurrentTime('');
      if (onChange) onChange('');
    } else {
      setCurrentTime(selectedTime);
      if (onChange) onChange(selectedTime);
    }
    setVisible(false);
  };

  const handlePress = () => {
    console.log('TimePicker pressed, disabled:', disabled);
    if (!disabled) {
      setVisible(true);
    }
  };

  const formatTime = (timeStr: string): string => {
    return timeStr ? timeStr : '不使用时间触发';
  };

  return (
    <>
      <TouchableOpacity 
        style={[styles.timeSelector, disabled && styles.disabled]}
        onPress={handlePress}
        disabled={disabled}
        activeOpacity={0.7}
      >
        <Text style={[styles.timeText, disabled && styles.disabledText]}>
          {currentTime ? formatTime(currentTime) : placeholder}
        </Text>
        <FontAwesome 
          name="clock-o" 
          size={16} 
          color={disabled ? "#ccc" : "#666"} 
        />
      </TouchableOpacity>
      
      <Picker
        data={timeOptions}
        cols={1}
        visible={visible}
        value={[currentTime]}
        onOk={handleTimeChange}
        onDismiss={() => setVisible(false)}
      />
    </>
  );
};

const styles = StyleSheet.create({
  timeSelector: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 12,
    paddingVertical: 10,
    backgroundColor: '#f5f5f5',
    borderRadius: 6,
    borderWidth: 1,
    borderColor: '#ddd',
    minHeight: 44,
  },
  timeText: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  disabled: {
    backgroundColor: '#f9f9f9',
    borderColor: '#e5e5e5',
  },
  disabledText: {
    color: '#ccc',
  },
});

export default TimePicker;